package com.hxk.task.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@RestController
public class MailController {

    /**
     * 注入mail-starter提供的mail类
     */
    @Autowired
    private JavaMailSenderImpl javaMailSender;

    /**
     * 发送简单格式的邮件
     * @return
     */
    @GetMapping("send")
    public String send(){
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom("345736612@qq.com");//必须和配置文件中的邮箱一致，不然会报异常
        simpleMailMessage.setSubject("开会通知");
        simpleMailMessage.setText("今晚20:00在会议室开扯淡大会！！！望准时参加！");
        simpleMailMessage.setTo("huixiaoke83@163.com");
        javaMailSender.send(simpleMailMessage);
        return "邮件发送成功! 请查收";
    }

    /**
     * 发送复杂格式的邮件
     * @return
     */
    @GetMapping("sendx")
    public String sendx(){
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setFrom("345736612@qq.com");//必须和配置文件中的邮箱一致，不然会报异常
            mimeMessageHelper.setSubject("开会通知");

            //设置html邮件内容体
            mimeMessageHelper.setText("<b><span style='color:red;'>今晚20:00在会议室开扯淡大会！！！望准时参加！</span></b>",true);

            //上传附件
            mimeMessageHelper.addAttachment("1.png",new File("F:\\其他\\电脑壁纸\\bz1 (1).jpg"));
            mimeMessageHelper.addAttachment("2.png",new File("F:\\其他\\电脑壁纸\\bz1 (2).jpg"));

            mimeMessageHelper.setTo("huixiaoke83@163.com");
            javaMailSender.send(mimeMessage);
            return "邮件发送成功! 请查收";
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return "邮件发送失败! 请联系系统管理员！";
    }
}
